package com.jxlc.web.api.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jxlc.web.api.system.domain.dto.FileDto;
import com.jxlc.web.api.system.domain.entity.SysFile;
import com.jxlc.web.api.system.mapper.SysFileMapper;
import com.jxlc.web.api.system.service.SysFileService;
import com.jxlc.common.config.ConfigConst;
import com.jxlc.common.constant.Constants;
import com.jxlc.common.exception.GlobalException;
import com.jxlc.common.utils.StringUtils;
import com.jxlc.common.utils.ZipUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class SysFileServiceImpl extends ServiceImpl<SysFileMapper, SysFile> implements SysFileService {

	@Override
	public FileDto insert(MultipartFile file) throws Exception {
		SysFile SysFile = new SysFile(file);
		this.save(SysFile);
		return BeanUtil.copyProperties(SysFile, FileDto.class);
	}

	@Override
	public List<FileDto> getFileByIds(Set<Long> ids) {
		if (ids.isEmpty()) {
			return Collections.emptyList();
		}
		return BeanUtil.copyToList(this.listByIds(ids), FileDto.class);
	}

	@Override
	public String downloadZip(String fileIdStr, String fileName) {
		List<Long> fileIds = StringUtils.str2LongList(fileIdStr);
		if (fileIds.isEmpty()) {
			throw new GlobalException("文件主键不能为空");
		}
		List<SysFile> files = baseMapper.selectBatchIds(fileIds);
		//解析后路径
		Set<String> filePath = files.stream().map(i -> i.getFilePath().replace(
				Constants.RESOURCE_PREFIX, ConfigConst.getProfile())).collect(Collectors.toSet());
		String zipName = fileName + ".zip";
		//压缩
		ZipUtils.compressFiles(zipName, filePath);
		return Constants.RESOURCE_PREFIX  + "/" + ConfigConst.getZipPath().substring(ConfigConst.getProfile().length() + 1) + "/" + zipName;
	}
}